package cn.itcast.aop;

import cn.itcast.mapper.OperateLogMapper;
import cn.itcast.pojo.EmpLoginLog;
import cn.itcast.pojo.OperateLog;
import cn.itcast.utils.ThreadLocalUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Arrays;

@Slf4j
@Component
@Aspect
public class LogOperatorAspect {
    @Autowired
    private OperateLogMapper operateLogMapper;

    @Around("execution(* cn.itcast.service.*.save*(..)) ||"+
    "execution(* cn.itcast.service.*.update*(..))||"+
    "execution(* cn.itcast.service.*.delete*(..))")
    public Object before(ProceedingJoinPoint joinPoint) throws Throwable {

        //获取操作人id
        Integer id =Integer.parseInt(ThreadLocalUtils.get().toString());
//获取类名
        String className = joinPoint.getTarget().getClass().getName();

        //获取方法名
        String methodName = joinPoint.getSignature().getName();

        //获取运行参数
        String methodParam = Arrays.toString(joinPoint.getArgs());


        long start = System.currentTimeMillis();
        //获取方法返回值
        Object obj = joinPoint.proceed();
        long end = System.currentTimeMillis();
        long recordTime = end - start;
        //返回参数
        String result = obj == null ? "void" : obj.toString();

        OperateLog.OperateLogBuilder builder = OperateLog.builder();

        OperateLog operateLog = OperateLog.builder().operateEmpId(id)
                .operateTime(LocalDateTime.now())
                .className(className)
                .methodName(methodName)
                .methodParams(methodParam)
                .returnValue(result)
                .costTime(recordTime)
                .build();

        //插入数据
        operateLogMapper.insert(operateLog);



        return obj;


    }

}
